<?php
namespace addons\sdcmarry\controller\api;

use addons\sdcmarry\model\Order as ModelOrder;
use addons\sdcmarry\model\Service;
use addons\sdcmarry\validate\Order as ValidateOrder;
use fast\Random;
use think\Loader;

class Order extends Api
{
    protected $noNeedLogin = ['user'];
    protected $noNeedRight = ['*'];

    private $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ModelOrder();
    }

    public function add()
    {
        $user = $this->auth->getUser();
        $formData = $this->request->post();
        $validate = Loader::validate(ValidateOrder::class);
        if(! $validate->check($formData)){
            $this->error($validate->getError());
        }
        if(! $service = Service::find($formData['service_id'])){
            $this->error(__('Service not found'));
        }
        $order = $this->model;
        $order->data($formData);
        $order->price = $service->new_price;
        $order->orderno = Random::numeric(12);
        $order->user_id = $user->id;
        $order->ordertime = strtotime($formData['ordertime']);
        if($result = $order->allowField(true)->save()){
            $this->success(__('Order created'),$order);
        }else{
            $this->error(__('Order create fail'));
        }
    }

}